<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h5>欢迎亲的登录：</h5>

    用户名：<input type="text" id="username" /><br />
    密码：<input type="password" id="userpass" /><br />
    <input id="btnLogin" type="button" value="登录" />
    <div id="msg"></div>
</body>

</html>
<script>
    let oBtnLogin = document.getElementById("btnLogin");
    let oUserPass = document.getElementById("userpass");
    let oUserName = document.getElementById("username");

    oBtnLogin.onclick = function () {
        let xhr = new XMLHttpRequest();
        xhr.open("post", "login.php", true);

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                if (xhr.responseText == 1) {
                    document.getElementById("msg").innerHTML = "登录成功";
                    location.href = "index.html"; //跳转到首页
                } else {
                    document.getElementById("msg").innerHTML = "登录失败,用户名或者密码错误";
                }
            }
        }

        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        let str = "username=" + oUserName.value + "&userpass=" + oUserPass.value;
        xhr.send(str);

    }


</script>